package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import android.util.Log;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import com.example.handheld4_gsignal_app.network.ApiClient;
import com.example.handheld4_gsignal_app.network.ApiResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI分析服务 - 提供信号质量分析、异常检测、模式识别等功能
 */
public class AIAnalysisService {
    
    private static final String TAG = "AIAnalysisService";
    private Context context;
    private ApiClient apiClient;
    private Gson gson;
    
    public AIAnalysisService(Context context) {
        this.context = context;
        this.apiClient = new ApiClient();
        this.gson = new Gson();
    }
    
    /**
     * 分析类型枚举
     */
    public enum AnalysisType {
        SIGNAL_QUALITY("signal_quality"),
        ANOMALY_DETECTION("anomaly_detection"),
        PATTERN_RECOGNITION("pattern_recognition");
        
        private final String value;
        
        AnalysisType(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * 严重程度枚举
     */
    public enum SeverityLevel {
        LOW("low"),
        MEDIUM("medium"),
        HIGH("high"),
        CRITICAL("critical");
        
        private final String value;
        
        SeverityLevel(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * AI分析结果
     */
    public static class AIAnalysisResult {
        private String analysisId;
        private String recordId;
        private String deviceId;
        private String analysisType;
        private String resultLabel;
        private double confidenceScore;
        private String severityLevel;
        private Map<String, Object> details;
        private String modelVersion;
        private int processingTimeMs;
        private String createdAt;
        
        // Getters and Setters
        public String getAnalysisId() { return analysisId; }
        public void setAnalysisId(String analysisId) { this.analysisId = analysisId; }
        
        public String getRecordId() { return recordId; }
        public void setRecordId(String recordId) { this.recordId = recordId; }
        
        public String getDeviceId() { return deviceId; }
        public void setDeviceId(String deviceId) { this.deviceId = deviceId; }
        
        public String getAnalysisType() { return analysisType; }
        public void setAnalysisType(String analysisType) { this.analysisType = analysisType; }
        
        public String getResultLabel() { return resultLabel; }
        public void setResultLabel(String resultLabel) { this.resultLabel = resultLabel; }
        
        public double getConfidenceScore() { return confidenceScore; }
        public void setConfidenceScore(double confidenceScore) { this.confidenceScore = confidenceScore; }
        
        public String getSeverityLevel() { return severityLevel; }
        public void setSeverityLevel(String severityLevel) { this.severityLevel = severityLevel; }
        
        public Map<String, Object> getDetails() { return details; }
        public void setDetails(Map<String, Object> details) { this.details = details; }
        
        public String getModelVersion() { return modelVersion; }
        public void setModelVersion(String modelVersion) { this.modelVersion = modelVersion; }
        
        public int getProcessingTimeMs() { return processingTimeMs; }
        public void setProcessingTimeMs(int processingTimeMs) { this.processingTimeMs = processingTimeMs; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
    }
    
    /**
     * 分析请求
     */
    public static class AnalysisRequest {
        private String recordId;
        private String deviceId;
        private String analysisType;
        private List<Map<String, Object>> signalData;
        
        public AnalysisRequest(String recordId, String deviceId, String analysisType, List<SignalRecord> signalRecords) {
            this.recordId = recordId;
            this.deviceId = deviceId;
            this.analysisType = analysisType;
            this.signalData = convertSignalRecordsToMap(signalRecords);
        }
        
        private List<Map<String, Object>> convertSignalRecordsToMap(List<SignalRecord> records) {
            List<Map<String, Object>> data = new ArrayList<>();
            for (SignalRecord record : records) {
                Map<String, Object> recordMap = new HashMap<>();
                recordMap.put("signal_strength", record.getSignalStrength());
                recordMap.put("latitude", record.getLatitude());
                recordMap.put("longitude", record.getLongitude());
                recordMap.put("collected_at", record.getCollectedAt());
                recordMap.put("network_type", record.getNetworkType());
                recordMap.put("operator_name", record.getOperatorName());
                recordMap.put("cell_id", record.getCellId());
                data.add(recordMap);
            }
            return data;
        }
        
        // Getters and Setters
        public String getRecordId() { return recordId; }
        public void setRecordId(String recordId) { this.recordId = recordId; }
        
        public String getDeviceId() { return deviceId; }
        public void setDeviceId(String deviceId) { this.deviceId = deviceId; }
        
        public String getAnalysisType() { return analysisType; }
        public void setAnalysisType(String analysisType) { this.analysisType = analysisType; }
        
        public List<Map<String, Object>> getSignalData() { return signalData; }
        public void setSignalData(List<Map<String, Object>> signalData) { this.signalData = signalData; }
    }
    
    /**
     * 分析回调接口
     */
    public interface AnalysisCallback {
        void onSuccess(AIAnalysisResult result);
        void onError(String error);
    }
    
    /**
     * 批量分析回调接口
     */
    public interface BatchAnalysisCallback {
        void onSuccess(List<AIAnalysisResult> results);
        void onError(String error);
    }
    
    /**
     * 执行AI分析
     */
    public void analyzeSignalData(String recordId, String deviceId, AnalysisType analysisType, 
                                 List<SignalRecord> signalRecords, AnalysisCallback callback) {
        try {
            AnalysisRequest request = new AnalysisRequest(recordId, deviceId, analysisType.getValue(), signalRecords);
            
            String requestJson = gson.toJson(request);
            Log.d(TAG, "发送AI分析请求: " + requestJson);
            
            apiClient.post("/api/v2/ai/analyze", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        AIAnalysisResult result = gson.fromJson(response, AIAnalysisResult.class);
                        Log.d(TAG, "AI分析成功: " + result.getResultLabel());
                        callback.onSuccess(result);
                    } catch (Exception e) {
                        Log.e(TAG, "解析AI分析结果失败", e);
                        callback.onError("解析分析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "AI分析失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "AI分析请求失败", e);
            callback.onError("分析请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量AI分析
     */
    public void batchAnalyzeSignalData(List<AnalysisRequest> requests, BatchAnalysisCallback callback) {
        try {
            String requestJson = gson.toJson(requests);
            Log.d(TAG, "发送批量AI分析请求，数量: " + requests.size());
            
            apiClient.post("/api/v2/ai/batch-analyze", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Type listType = new TypeToken<List<AIAnalysisResult>>(){}.getType();
                        List<AIAnalysisResult> results = gson.fromJson(response, listType);
                        Log.d(TAG, "批量AI分析成功，结果数量: " + results.size());
                        callback.onSuccess(results);
                    } catch (Exception e) {
                        Log.e(TAG, "解析批量AI分析结果失败", e);
                        callback.onError("解析分析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "批量AI分析失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "批量AI分析请求失败", e);
            callback.onError("批量分析请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 本地信号质量分析（简化版）
     */
    public AIAnalysisResult analyzeSignalQualityLocally(List<SignalRecord> signalRecords) {
        if (signalRecords == null || signalRecords.isEmpty()) {
            return createEmptyResult("无数据", 0.0, SeverityLevel.LOW);
        }
        
        try {
            // 计算平均信号强度
            double avgSignal = 0;
            int minSignal = Integer.MAX_VALUE;
            int maxSignal = Integer.MIN_VALUE;
            
            for (SignalRecord record : signalRecords) {
                int signal = record.getSignalStrength();
                avgSignal += signal;
                minSignal = Math.min(minSignal, signal);
                maxSignal = Math.max(maxSignal, signal);
            }
            avgSignal /= signalRecords.size();
            
            // 质量评估
            String qualityLabel;
            double confidence;
            SeverityLevel severity;
            
            if (avgSignal >= -70) {
                qualityLabel = "优秀";
                confidence = 0.95;
                severity = SeverityLevel.LOW;
            } else if (avgSignal >= -85) {
                qualityLabel = "良好";
                confidence = 0.85;
                severity = SeverityLevel.LOW;
            } else if (avgSignal >= -100) {
                qualityLabel = "一般";
                confidence = 0.75;
                severity = SeverityLevel.MEDIUM;
            } else {
                qualityLabel = "较差";
                confidence = 0.90;
                severity = SeverityLevel.HIGH;
            }
            
            // 创建结果
            AIAnalysisResult result = new AIAnalysisResult();
            result.setAnalysisId("local_" + System.currentTimeMillis());
            result.setRecordId("local_record");
            result.setDeviceId("local_device");
            result.setAnalysisType(AnalysisType.SIGNAL_QUALITY.getValue());
            result.setResultLabel(qualityLabel);
            result.setConfidenceScore(confidence);
            result.setSeverityLevel(severity.getValue());
            result.setModelVersion("local_v1.0");
            result.setProcessingTimeMs(10);
            result.setCreatedAt(String.valueOf(System.currentTimeMillis()));
            
            // 添加详细信息
            Map<String, Object> details = new HashMap<>();
            details.put("avg_signal_strength", avgSignal);
            details.put("min_signal_strength", minSignal);
            details.put("max_signal_strength", maxSignal);
            details.put("total_records", signalRecords.size());
            result.setDetails(details);
            
            return result;
            
        } catch (Exception e) {
            Log.e(TAG, "本地信号质量分析失败", e);
            return createEmptyResult("分析失败", 0.0, SeverityLevel.HIGH);
        }
    }
    
    /**
     * 创建空结果
     */
    private AIAnalysisResult createEmptyResult(String label, double confidence, SeverityLevel severity) {
        AIAnalysisResult result = new AIAnalysisResult();
        result.setAnalysisId("empty_" + System.currentTimeMillis());
        result.setRecordId("empty_record");
        result.setDeviceId("empty_device");
        result.setAnalysisType(AnalysisType.SIGNAL_QUALITY.getValue());
        result.setResultLabel(label);
        result.setConfidenceScore(confidence);
        result.setSeverityLevel(severity.getValue());
        result.setModelVersion("empty_v1.0");
        result.setProcessingTimeMs(0);
        result.setCreatedAt(String.valueOf(System.currentTimeMillis()));
        result.setDetails(new HashMap<>());
        return result;
    }
}